package com.myapp.RN;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;
import androidx.annotation.Nullable;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.gizwits.gizwifisdk.api.GizWifiDevice;
import com.gizwits.gizwifisdk.enumration.GizWifiErrorCode;
import com.gizwits.gizwifisdk.listener.GizWifiDeviceListener;
import com.myapp.Activity.GizType;
import com.myapp.Activity.MainActivity;
import com.myapp.Data.GizManger;
import com.myapp.EventBus.EventBusUtil;
import com.myapp.EventBus.GizMessageEvent;
import com.myapp.utils.HexStrUtils;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.annotation.Nonnull;

import static com.myapp.MainApplication.PRODUCT_S;


public class OpenNativeModule extends  ReactContextBaseJavaModule {
    private static final String TAG = "OpenNativeModule";

    private ReactContext mContext;


    // 数据点"SystemPower"对应的标识名
    private static final String KEY_SYSTEMPOWER = "SystemPower";
    // 数据点"SystemFan"对应的标识名
    private static final String KEY_SYSTEMFAN = "SystemFan";
    // 数据点"ErrorImfor"对应的标识名
    private static final String KEY_ERRORIMFOR = "ErrorImfor";
    // 数据点"RoomTemp"对应的标识名
    private static final String KEY_ROOMTEMP = "RoomTemp";
    // 数据点"SaunaRunTime"对应的标识名
    private static final String KEY_SAUNARUNTIME = "SaunaRunTime";
    // 数据点"SystemLight"对应的标识名
    private static final String KEY_SYSTEMLIGHT = "SystemLight";
    // 数据点"SaunaStateTimeTemp"对应的标识名
    private static final String KEY_SAUNASTATETIMETEMP = "SaunaStateTimeTemp";
    // 数据点"FMBT_StateFreqVol"对应的标识名
    private static final String KEY_FMBT_STATEFREQVOL = "FMBT_StateFreqVol";
    // 数据点"FMBT_16_Freq"对应的标识名
    private static final String KEY_FMBT_16_FREQ = "FMBT_16_Freq";
    private GizManger gizManger;
    private GizWifiDevice mDevice;

    private GizWifiDevice gizWifiDevice = GizManger.getInstance().getDevice();
    public OpenNativeModule(@Nonnull ReactApplicationContext reactContext) {
        super(reactContext);
        mContext = reactContext;
        GizManger.getInstance().init(mContext);
        EventBusUtil.register(this);
    }
    private GizType gizType = GizType.DEVICE_ONELIGHT;

    @Nonnull
    @Override
    public String getName() {
        return "OpenNativeModule";
    }

    @ReactMethod
    public void jump2Native(ReadableMap map, Promise promise){
        ReadableMap readableMap = map.getMap("data");
        String deviceName = readableMap.getString("deviceName");
        String value = readableMap.getString("value");
        gizManger = GizManger.getInstance();
        assert deviceName != null;
        switch (deviceName){
            case "Device_SystemPower":
                gizManger.sendCommand(KEY_SYSTEMPOWER,value);
                break;
            case "Device_SystemFan" :
                gizManger.sendCommand(KEY_SYSTEMFAN,value);
                break;
            case "Device_OneLight" :
                gizType = GizType.DEVICE_ONELIGHT;
                gizType.setValue(value);
                GizManger.getInstance().sendCommand(KEY_SYSTEMLIGHT, HexStrUtils.hexStringToBytes(lightTranfor().replaceAll(" ", "")));
                break;
            case "Device_TwoLight" :
                gizType = GizType.DEVICE_TWOLIGHT;
                gizType.setValue(value);
                GizManger.getInstance().sendCommand(KEY_SYSTEMLIGHT, HexStrUtils.hexStringToBytes(lightTranfor().replaceAll(" ", "")));
                break;
            //桑拿状态，时间，温度
            case "Device_SaunaStateTimeTemp" :
                gizManger.sendCommand(KEY_SAUNASTATETIMETEMP,HexStrUtils.hexStringToBytes(value));
                break;
            //控制FM收音功能和蓝牙播放功能状态、FM收音功能的频率、FM收音功能或蓝牙功能的音量
            case "Device_FMBT_StateFreqVol" :
                gizManger.sendCommand(KEY_FMBT_STATEFREQVOL,HexStrUtils.hexStringToBytes(value));
                break;
            //只读 当前的FM收音机保存的16个电台频率
            case "Device_FMBT_16_Freq" :
               // return KEY_FMBT_16_FREQ;
                break;
            //故障信息
            case "Device_ErrorImfor" :
               // return KEY_ERRORIMFOR;
                break;
            //桑拿房当前温度
            case "Device_RoomTemp" :
                //return KEY_ROOMTEMP;
                break;
            //桑拿运行时间
            case "Device_SaunaRunTime" :
                //return KEY_SAUNARUNTIME;
                break;
            default:
                break;
        }
          if (1==1) {
       Log.i(TAG, "jump2Native: " +map);
       promise.resolve(value);
   } else {
       promise.reject("warning","data cannot be empty!");
   }
   }

   private String lightTranfor(){
       String one = GizType.values()[0].getValue();
       String two = GizType.values()[1].getValue();
       String status = "00";
       if (one.equals("0")){
           if (two.equals("1")){
               status = "02";
           } else{
               status = "00";
           }
       } else {
           if (two.equals("1")) {
               status = "03";
           } else {
               status = "01";
           }

       }
       return status;
   }
    @ReactMethod
    public void jumpToNativeView() {
        Intent intent = new Intent();
        intent.setClass(mContext, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        mDevice = GizManger.getInstance().getDevice();
        mDevice.setSubscribe(PRODUCT_S, false);
        mContext.startActivity(intent);
    }




    /**
     * RN获取原生端定义的常量
     * @return
     */
    @Nullable
    @Override
    public Map<String, Object> getConstants() {
        Map<String, Object> params = new HashMap<>();
        params.put("CustomConstant", "我是Android端定义的常量");
        params.put("ToastLONG", Toast.LENGTH_LONG);
        params.put("ToastSHORT", Toast.LENGTH_SHORT);
        return params;
    }

    /**
     * RN向原生传递字符串
     * @param s
     */
    @ReactMethod
    public void getStringFromReactNative(String s) {
        Toast.makeText(mContext, s, Toast.LENGTH_SHORT).show();
    }


    /**
     * RN向原生传递Int
     * @param i
     */
    @ReactMethod
    public void getIntFromReactNative(Integer i) {
        Toast.makeText(mContext, "" + i, Toast.LENGTH_SHORT).show();
    }

    /**
     * RN向原生传递字典。这里原生端接收RN传过来的字典类型是ReadableMap
     * @param map
     */
    @ReactMethod
    public void getDictionaryFromRN(ReadableMap map) {
        System.out.print(map);
        Toast.makeText(mContext, "已收到字典数据", Toast.LENGTH_SHORT).show();
    }

    /**
     * RN向原生传递数组
     * @param array
     */
    @ReactMethod
    public void getArrayFromRN(ReadableArray array) {
        System.out.print(array);
        Toast.makeText(mContext, "已收到数组数据", Toast.LENGTH_SHORT).show();
    }

    /**
     * 原生通过回调的形式向RN端传递string
     * @param callback
     */
    @ReactMethod
    public void passStringBackToRN(Callback callback) {
        callback.invoke("This is a string from Native");
    }

    /**
     * 原生通过回调的形式向RN端传递字典。这里传出去的字典类型必须是WritableMap，java中的Map、HashMap是不能传递到RN的
     * @param callback
     */
    @ReactMethod
    public void passDictionaryBackToRN(Callback callback) {
        WritableMap map = Arguments.createMap();
        map.putString("name", "小明");
        map.putInt("age", 20);
        map.putString("gender", "male");
        map.putBoolean("isGraduated", true);
        callback.invoke(map);
    }

    @ReactMethod
    public void passArrayBackToRN(Callback callback) {
        WritableArray array = Arguments.createArray();
        array.pushString("React Native");
        array.pushString("Android");
        array.pushString("iOS");
        callback.invoke(array);
    }

    @ReactMethod
    public void passPromiseBackToRN(String msg, Promise promise) {
        if (!msg.equals("")) {
            promise.resolve(true);
        } else {
            promise.reject("warning", "msg cannot be empty!");
        }
    }



    public void sendEvent(String eventName) {
        WritableMap dataToRN = GizManger.getInstance().tranfor();
        mContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit(eventName, dataToRN);
        Log.i(TAG, "sendEvent: ");
    }


   @Subscribe(threadMode = ThreadMode.MAIN,priority = 0)
    public void onGizChange(GizMessageEvent event){
       Log.i(TAG, "onGizChange: " +"收到eventbus");
       sendEvent("CustomEventName");
   }
}
